package com.zhiyou100.blog.aciton.title;

import com.zhiyou100.blog.entity.PageBean;
import com.zhiyou100.blog.entity.Title;
import com.zhiyou100.blog.service.TitleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author shkstart
 * @create 2021-10-23 22:12
 */
@WebServlet("/title/query")
public class TitleQueryServlet extends HttpServlet {
    private TitleService service = new TitleService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String queryText = request.getParameter("queryText");
        String pageNum = request.getParameter("pageNum");
        if (pageNum == null || "".equals(pageNum)) {
            pageNum = "1";
        }
        HttpSession session = request.getSession();
        session.removeAttribute("titlePage");

        //如果带有 查询问题就进行查询分页没有就是普通的分页查询
        if (queryText != null && !"".equals(queryText)) {
            //封装 查询
            TitleService service = new TitleService();
            PageBean<Title> titlePage = service.queryListTitlePagingByQustion(Integer.parseInt(pageNum), queryText);
            System.out.println("titlePage = " + titlePage);
            request.getSession().setAttribute("titlePage", titlePage);
        }
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNum = request.getParameter("pageNum"); //如果不传入参数默认时第一页
        if (pageNum == null) {
            pageNum = "1";
        }
        HttpSession session = request.getSession();
        session.removeAttribute("titlePage");
        session.removeAttribute("queryText"); //删除查询条件
        //普通查询
        System.out.println("pageNum = " + pageNum);
        PageBean<Title> titlePage = service.getListTitlePaging(Integer.parseInt(pageNum));
        System.out.println("titlePage = " + titlePage);

        session.setAttribute("titlePage", titlePage);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
